<?php

namespace App\Console\Commands;

use App\Library\Logger;
use App\Models\Event;
use App\Models\UserModel;
use App\Repositories\WorkOrderRepo;
use App\Services\SmsService;
use Carbon\Carbon;
use Illuminate\Console\Command;

class WorkOrderTimeoutNotify extends Command
{

    const SMS_TIMEOUT = [
        'sms_code' => 'SMS_463685456',
        'variables' => [
            'count'
        ]
    ];

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'work_order:timeout_notify';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '超时工单短信通知';
    private $log = null;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->log = new Logger('command/work_order/timeout_notify');
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $bench = new \Ubench();
        $bench->start();

        $this->action();

        $bench->end();
        $this->log->debug("Time used: " . $bench->getTime());
        $this->log->debug("Memory Used: " . $bench->getMemoryUsage());
    }

    /**
     * 对象: 售后总监 + 售后经理
     * @return void
     */
    private function action()
    {
        $users = $this->getUsers();
        $this->log->info("发送通知");
        if (empty($users)) {
            $this->log->notice("无客户数据，返回...");
            return;
        }
        foreach ($users as $user) {
            $itemUserId = $user['id'];
            $itemUserName = $user['realname'];
            $itemMobile = $user['mobile'];
            $statusCounts = WorkOrderRepo::statusTimeoutCounts($itemUserId);
            $this->log->info("姓名: {$itemUserName}, 电话: {$itemMobile}, 超时工单量: {$statusCounts}");
            if ($statusCounts <= 0) {
                continue;
            }
            $this->sendSms($itemMobile, self::SMS_TIMEOUT, ['count' => $statusCounts]);
        }
    }

    private function sendSms($telephone, $template, $params = [])
    {
        $smsCode = $template['sms_code'];
        $smsService = new SmsService($telephone);
        try {
            $smsService->sendMessage($smsCode, $params);
        } catch (\Exception $e) {
            $logger = new Logger('sms/work_order');
            $logger->error($e->getMessage());
        }
    }

    private function getUsers()
    {
        $positionName = ['售后总监', '售后经理'];
        $builder = UserModel::query()
            ->from('user as u')
            ->join('position as p', 'p.id', '=', 'u.position_id')
            ->whereIn('p.name', $positionName)
            ->where('u.mobile', '<>', '')
            ->where('u.mark', '=', 1)
            ->select(['u.id', 'u.mobile', 'p.name', 'u.realname']);
        return $builder->get()->toArray();
    }
}
